package com.haochang.chunkvod.controller.fragment.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseEditText;
import com.haochang.base.BaseFragment;
import com.haochang.base.BaseTextView;
import com.haochang.base.EventProxy;
import com.haochang.base.IEventConstant;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.config.ApiConfig;
import com.haochang.chunkvod.app.database.order.GoodsInfoDao;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.adapter.order.CartExpandableAdapter;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.OrderData;
import com.haochang.chunkvod.model.order.ShopCartData;
import com.haochang.chunkvod.tools.vod.event.EventObserver;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.view.vod.activity.AuthorizationDialogActivity;
import com.haochang.chunkvod.view.vod.activity.SingleInputActivity;
import com.haochang.chunkvod.view.vod.popupWindow.VodPopWindow;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;

/**
 * @author qintao
 *         created at 2016/6/13 10:38
 *         购物车
 */

public class ShopCartFragment extends BaseFragment implements EventObserver
{
	private TitleView titleView;
	private CheckBox item_cb;
	private BaseTextView tv_clear_cart;
	private BaseTextView tv_totalPrice;
	private Button btn_xia_dan;
	private BaseEditText et_delivery_address;//外带填写地址
	private ExpandableListView ex_listView;
	private CartExpandableAdapter adapter;
	private ShopCartData shopCartData;
	private OrderData orderData;

	private String roomNum;
	private String roomId;
	private String billId;
	private String roomStatus;//房间状态
	private int type;//类型
	private List<GoodsInfo> goodsInfoList = new ArrayList<GoodsInfo>();
	private List<GoodsInfo> infoList = new ArrayList<GoodsInfo>();
	private JSONArray goodsArray = null;
	private String token = "";
	private boolean isTakeOut = false;//是否是外带
	//	private boolean isLocalNeedBillId = true;

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
	{
		return inflater.inflate(R.layout.activity_shopping_cart, container, false);
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState)
	{
		super.onActivityCreated(savedInstanceState);
		EventProxy.addEventListener(this, IEventConstant.EVENT_SHOP_CART_PRICE);
		initView();
		initData();
	}

	private void initData()
	{
		goodsInfoList = GoodsInfoDao.getDao().queryBuilderAll(GoodsInfo.class, "bill_id", billId);
		shopCartData = new ShopCartData((BaseActivity) getActivity());
		orderData = new OrderData((BaseActivity) getActivity());
		shopCartData.requestShopCartStatus(billId, getGoodsIds(goodsInfoList), getActiveIds(goodsInfoList), new ShopCartData.IShopCartStatusListener()
		{
			@Override
			public void onRequestSuccess(List<GoodsInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					infoList.addAll(list);
					for (GoodsInfo info : goodsInfoList)
					{
						for (GoodsInfo goodInfo : infoList)
						{
							if (info.getGoodsId().equals(goodInfo.getGoodsId()))
							{
								info.setSurplus(goodInfo.getSurplus());
								break;
							}
						}
					}
					adapter.setData(goodsInfoList);
					tv_totalPrice.setText(SaleUtils.getSaleString(getTotalPrice(goodsInfoList)));
				}
			}
		});
	}

	private void initView()
	{
		isTakeOut = getArguments().getBoolean(IntentKey.ORDER_TAKEOUT);
		roomNum = getArguments().getString(IntentKey.ROOM_NUM);
		roomId = getArguments().getString(IntentKey.ROOM_ID);
		billId = getArguments().getString(IntentKey.BILL_ID);
		roomStatus = getArguments().getString(IntentKey.ROOM_STATUS);
		type = getArguments().getInt(IntentKey.ROOM_TYPE);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(roomNum).setBackText("主页").setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				getActivity().finish();
			}

			@Override
			public void onDoneClick()
			{
				{
					List<String> list = new ArrayList<String>();
					list.add("退出登录");
					int location[] = new int[2];
					ImageView img = (ImageView) titleView.findViewById(R.id.img_operates);
					img.getLocationOnScreen(location);
					int x = location[0];
					final VodPopWindow pop = new VodPopWindow(getActivity(), list);
					pop.showPopupWindow(titleView, x);
					pop.setPopWindowListListener(new VodPopWindow.OnPopWindowListListener()
					{
						@Override
						public void onSelectItem(int position)
						{
							switch (position)
							{
							case 0:
								((BaseActivity) getActivity()).loginOut();
								break;
							default:
								break;
							}
						}
					});
				}
			}
		});
		item_cb = (CheckBox) findViewById(R.id.item_cb);
		item_cb.setChecked(true);
		if (isTakeOut)
		{
			FrameLayout frameLayout = (FrameLayout) findViewById(R.id.includeAddress);
			frameLayout.setVisibility(View.VISIBLE);
			et_delivery_address = (BaseEditText) frameLayout.findViewById(R.id.et_delivery_address);
			et_delivery_address.requestFocus();
			et_delivery_address.post(new Runnable()
			{
				@Override
				public void run()
				{
					et_delivery_address.setText(getText(R.string.on_the_stage));
					et_delivery_address.setSelection(et_delivery_address.getText() == null ? 0 : et_delivery_address.getText().toString().length());
				}
			});
			item_cb.setVisibility(View.GONE);
		}
		tv_clear_cart = (BaseTextView) findViewById(R.id.tv_clear_cart);
		tv_clear_cart.setOnClickListener(mOnBaseClickListener);
		tv_totalPrice = (BaseTextView) findViewById(R.id.tv_totalPrice);
		btn_xia_dan = (Button) findViewById(R.id.btn_xia_dan);
		btn_xia_dan.setOnClickListener(mOnBaseClickListener);
		ex_listView = (ExpandableListView) findViewById(R.id.ex_listView);
		goodsInfoList.clear();
		adapter = new CartExpandableAdapter(this, getActivity(), goodsInfoList);
		ex_listView.setAdapter(adapter);
	}

	private OnBaseClickListener mOnBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(View v)
		{
			switch (v.getId())
			{
			case R.id.tv_clear_cart:
				new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(true).contentName("确认要清空购物车吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								goodsInfoList.clear();
								ShoppingCartManager.clearGoods(billId);
								adapter.setData(new ArrayList<GoodsInfo>());
								tv_totalPrice.setText(String.valueOf(0));
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			case R.id.btn_xia_dan:
				if (CollectionUtils.isEmpty(goodsInfoList))
				{
					ToastUtils.showText(getActivity(), "请选择商品");
					return;
				}
				if (isTakeOut && TextUtils.isEmpty(et_delivery_address.getText().toString()))
				{
					ToastUtils.showText(getActivity(), "请输入地址");
					return;
				}
				if (!isSurplusNumSatisfy(goodsInfoList))
					return;
				goodsArray = new JSONArray();
				for (GoodsInfo goodsInfo : goodsInfoList)
				{
					JSONObject jsonObject = ShoppingCartManager.getGoodsDataJson(goodsInfo);
					goodsArray.put(jsonObject);
				}
				if (isExitGiveGoods(goodsInfoList))
				{
					Intent intent = new Intent(getActivity(), AuthorizationDialogActivity.class);
					if (isTakeOut)
						intent.putExtra(IntentKey.TOKEN_EVENT, "门店POS系统>点餐系统模块>点餐>外带赠送");//传入权限验证事件名
					else
						intent.putExtra(IntentKey.TOKEN_EVENT, "门店POS系统>点餐系统模块>点餐>赠送");//传入权限验证事件名
					intent.putExtra(IntentKey.INTERFACE_NAME, ApiConfig.VOD_TOKEN);//传入接口名字
					startActivityForResult(intent, IntentCode.SHOP_CART_REQUEST_PERMISSION);
				} else
				{
					token = "";
					//					if (isDeskPaiedCapacity())
					//						deskFree();
					if (TextUtils.isEmpty(billId))
						onPeopleCountClick();
					else
						placeOrder(null, "", isTakeOut ? et_delivery_address.getText().toString() : null);
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 购物车下单
	 * @param  address 外带地址
	 * @param token 审核人token
	 */
	private void placeOrder(JSONObject deskInfo, String token, String address)
	{
		if (goodsArray != null && goodsArray.length() >= 0)
			shopCartData.requestShopCartGoods(deskInfo, roomId, billId, address, goodsArray, token, item_cb.isChecked() ? 1 : 0,
					new ShopCartData.IShopCartGoodsListener()
					{
						@Override
						public void onRequestSuccess(String msg, String bill_id)
						{
							ToastUtils.showText(getActivity(), "下单成功");
							if (!TextUtils.isEmpty(msg))
							{
								new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.ONLY_TOAST).cancelable(true)
										.contentName("已为您自动添加以下优惠活动：" + msg).onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
										{
											@Override
											public void onOnlyCancelClick()
											{
											}

											@Override
											public void onOkClick()
											{
											}

											@Override
											public void onCancelClick()
											{
											}
										}).build().show();
							}
							ShoppingCartManager.clearGoods(billId);
							goodsInfoList.clear();
							adapter.setData(goodsInfoList);
							tv_totalPrice.setText("0");
							if (!TextUtils.isEmpty(bill_id))
							{
								billId = bill_id;
								//								if (type == 1)//桌台
								//								{
								//									roomStatus = "using";
								//									EventProxy.notifyEvent(IEventConstant.EVENT_DESK_STATUS, roomStatus, billId);
								//								}
							}
						}

						@Override
						public void onFail(int errno, String errMsg)
						{
							ToastUtils.showText(getActivity(), errMsg);
							if (errno == 4202 || errno == 4216)//账单已完成or剩余数量不足提示,不能点餐,清空购物车
							{
								ShoppingCartManager.clearGoods(billId);
							}
						}
					});
	}

	/**
	 * 桌台转换为空台
	 */
	private void deskFree()
	{
		new VodDialog.Builder(getActivity()).dialogEnum(VodDialog.DialogEnum.DOUBLE).cancelable(true).contentName("是否要清空原桌台?").btnNegativeText("否")
				.btnNeutralText("是").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
				{
					@Override
					public void onOnlyCancelClick()
					{
					}

					@Override
					public void onOkClick()
					{
						orderData.requestDeskFree(roomId, billId, new OrderData.IDeskFreeListener()
						{
							@Override
							public void onRequestSuccess()
							{
								billId = "";
								//								isLocalNeedBillId = true;
								roomStatus = "empty";
								EventProxy.notifyEvent(IEventConstant.EVENT_DESK_STATUS, roomStatus, billId);
								onPeopleCountClick();
							}

							@Override
							public void onFail(int errno, String errMsg)
							{
								if (!TextUtils.isEmpty(errMsg))
									ToastUtils.showText(getActivity(), errMsg);
							}
						});
					}

					@Override
					public void onCancelClick()
					{
						//						isLocalNeedBillId = false;
						onPeopleCountClick();
					}
				}).build().show();
	}

	/**
	 * 桌台买单未离下单弹框提示
	 */
	private boolean isDeskPaiedCapacity()
	{
		if (TextUtils.equals(roomStatus, "paied") && type == 1)
			return true;
		else
			return false;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (data != null && requestCode == IntentCode.SHOP_CART_REQUEST && resultCode == Activity.RESULT_OK)
		{
			//从有口味的选择框返回，此时查询新的数据
			if (data.getBooleanExtra(IntentKey.SHOPCART_REFRUSH_DATA, false))
			{
				goodsInfoList.clear();
				goodsInfoList.addAll(GoodsInfoDao.getDao().queryBuilderAll(GoodsInfo.class, "bill_id", billId));
				int totalNum = 0;
				for (GoodsInfo info : goodsInfoList)
				{
					totalNum += info.getOrderNum();
					for (GoodsInfo goodInfo : infoList)
					{
						if (info.getGoodsId().equals(goodInfo.getGoodsId()))
						{
							info.setSurplus(goodInfo.getSurplus());
							break;
						}
					}
				}
				adapter.setData(goodsInfoList);
				//				EventProxy.notifyEvent(IEventConstant.EVENT_ORDER_SHOP_CART, totalNum);
			} else
			{
				//从无口味的选择框返回
				GoodsInfo goodsInfo = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
				if (goodsInfo != null)
				{
					int totalNum = 0;
					for (GoodsInfo info : goodsInfoList)
					{
						if (TextUtils.equals(goodsInfo.getGoodsId(), info.getGoodsId()) && TextUtils.equals(goodsInfo.getStandard(), info.getStandard())
								&& goodsInfo.is_give() == info.is_give() && info.getId() == goodsInfo.getId())
							info.setOrderNum(goodsInfo.getOrderNum());
						totalNum += info.getOrderNum();
					}
					adapter.updateData(goodsInfo);
					//					EventProxy.notifyEvent(IEventConstant.EVENT_ORDER_SHOP_CART, totalNum);
				}
			}
			tv_totalPrice.setText(SaleUtils.getSaleString(getTotalPrice(goodsInfoList)));
		} else if (data != null && requestCode == IntentCode.SHOP_CART_REQUEST_PERMISSION && resultCode == Activity.RESULT_OK)
		{
			token = data.getStringExtra(IntentKey.GRANT_DIALOG_TOKEN);
			//			if (isDeskPaiedCapacity())
			//				deskFree();
			if (TextUtils.isEmpty(billId))
				onPeopleCountClick();
			else
				placeOrder(null, token, isTakeOut ? et_delivery_address.getText().toString() : null);
		} else if (requestCode == IntentCode.ROOM_PEOPLE_REQUEST && resultCode == Activity.RESULT_OK && data != null)
		{
			String people_count = data.getStringExtra(IntentKey.CUSTOM_DIALOG_CONTENT);
			JSONObject deskInfo = new JSONObject();
			try
			{
				deskInfo.put("desk_id", roomId);
				deskInfo.put("customer_count", people_count);
				placeOrder(deskInfo, token, isTakeOut ? et_delivery_address.getText().toString() : null);
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		}
	}

	/**
	 * 点击修改顾客人数
	 *
	 */
	private void onPeopleCountClick()
	{
		Intent intent1 = new Intent(getActivity(), SingleInputActivity.class);
		intent1.putExtra(IntentKey.CUSTOM_DIALOG_TITLE, "人数");
		intent1.putExtra(IntentKey.BTN_SURE, "确定");
		intent1.putExtra(IntentKey.BTN_CANCEL, "取消");
		intent1.putExtra(IntentKey.ACTIVITY_ENUM, SingleInputActivity.ActivityEnum.ROOM_NUMBERS);
		startActivityForResult(intent1, IntentCode.ROOM_PEOPLE_REQUEST);
	}

	/**
	 *   下单时获取商品ids
	 */
	private String getGoodsIds(List<GoodsInfo> list)
	{
		StringBuffer sb = new StringBuffer();
		if (CollectionUtils.isEmpty(list))
			return "";
		for (GoodsInfo info : list)
		{
			if (info.getGoods_type() == VodConstant.BUNDLE_TYPE || info.getGoods_type() == VodConstant.RETAIL_TYPE)
			{
				sb.append(info.getGoodsId() + ",");
			}
		}
		return sb.toString();
	}

	/**
	 *   下单时获取活动ids
	 */
	private String getActiveIds(List<GoodsInfo> list)
	{
		StringBuffer sb = new StringBuffer();
		if (CollectionUtils.isEmpty(list))
			return "";
		for (GoodsInfo info : list)
		{
			if (info.getGoods_type() == VodConstant.ACTIVE_TYPE)
			{
				sb.append(info.getGoodsId() + ",");
			}
		}
		return sb.toString();
	}

	/**
	 * 计算总计
	 *
	 * @param list
	 * @return
	 */
	private int getTotalPrice(List<GoodsInfo> list)
	{
		int total = 0;
		if (CollectionUtils.isEmpty(list))
			return 0;
		for (GoodsInfo info : list)
		{
			if (!info.is_give() && !info.is_present())
				total += info.getPrice() * info.getOrderNum();
		}
		return total;
	}

	/**
	 * 判断剩余数量是否满足条件
	 * @return
	 */
	private boolean isSurplusNumSatisfy(List<GoodsInfo> list)
	{
		for (int i = 0; i < list.size(); i++)
		{
			GoodsInfo goodsInfo = list.get(i);
			if (goodsInfo.getSurplus() < goodsInfo.getOrderNum())
			{
				ToastUtils.showText(getActivity(), goodsInfo.getGoodsName() + "仅剩" + goodsInfo.getSurplus() + goodsInfo.getUnit());
				return false;
			}
		}
		return true;
	}

	/**
	 * 判断是否存在增送模式下的商品
	 * @return
	 */
	private boolean isExitGiveGoods(List<GoodsInfo> list)
	{
		for (int i = 0; i < list.size(); i++)
		{
			GoodsInfo goodsInfo = list.get(i);
			if (goodsInfo.is_give())
				return true;
		}
		return false;
	}

	@Override
	public void onDestroy()
	{
		EventProxy.removeEventListener(IEventConstant.EVENT_SHOP_CART_PRICE, this);
		super.onDestroy();
	}

	@Override
	public void onNotify(Object sender, int eventId, Object... args)
	{
		GoodsInfo goodsInfo = (GoodsInfo) args[0];
		if (!CollectionUtils.isEmpty(goodsInfoList) && goodsInfoList.contains(goodsInfo))
			goodsInfoList.remove(goodsInfo);
		if (!goodsInfo.is_give() && !goodsInfo.is_present())
		{
			int price = goodsInfo.getPrice() * goodsInfo.getOrderNum();
			tv_totalPrice.setText(SaleUtils.getSaleString(SaleUtils.getSaleInt(tv_totalPrice.getText().toString()) - price));
		}
	}
}
